// 页面中组件或者按钮配置的操作 封装
// 传过来操作的配置
import React, { PureComponent } from "react";
import { Modal, Toast } from "antd-mobile";
import MToast from "../Util/MToast"
import { isNull, goToPage, handleDataType, filterExp, backToPrevious, calcField } from "../../utils/helper";
import getDataSource from "../MDatasource"
export default function MAction(props, acfg) {
	console.log("event_key", acfg);
	let events;
	try {
		events = props.config.events;
	}
	catch (e) {
		events = props.fd.config.events;
	}
	if (isNull(events)) {
		acfg = null;
	}
	else {
		if (!isNull(acfg)) {
			acfg = events[acfg]
		}
	}
	if (isNull(acfg)) {
		console.log("acfg不存在");
		return;
	}
	console.log("acfg存在", acfg, props);
	let newFormData = props.formData;
	try {
		let { fd: { formData } } = props;
		newFormData = {
			...formData,
			...props.formData
		}
	}
	catch (e) {

	}
	let { is_hex } = acfg;
	if (is_hex == 1) {//需要对formData 进行处理，根据规则转成16进制然后拼接
		newFormData = handleDataType(fields, newFormData);
	}
	console.log("newFormData", newFormData)
	props = {
		...props,
		acfg,
		formData: {
			...newFormData
		}
	};
	// callbackEventBack(props);
	if (browser.isInApp) {
		window._event_back_props = props;
		// 在event里面配置back 如果是在app里面就根据配置的back 注册事件， 当页面返回的时候 调用这个事件 
		Func.registerHanderBridge("callbackEventBack", callbackEventBack);
	}
	handleBefore(props);
}
function callbackEventBack() {
	let props = window._event_back_props;
	// Modal.alert("callbackEventBack");
	let { acfg, formData, dispatch, formDataKey } = props;


	let { back } = acfg;
	if (!isNull(back)) {
		let { row_api_key, api_key, dataset_key, refresh_all } = back;
		if (refresh_all == 1) {
			dispatch({
				type: "global/isChangeRefreshing",
				payload: {
					key: formDataKey
				}
			})
			return;
		}
		let config;
		try {
			config = props.fd.config
		}
		catch (e) {
			config = props.config;
		}
		let { apis, datasets } = config || {};
		if (!isNull(apis) && !isNull(row_api_key) && !isNull(apis[row_api_key])) {//请求info 更新当前一条数据
			// Modal.alert("row_api_key");
			let obj = {
				apiInfo: apis[row_api_key],
				data: formData
			};
			dispatch({// 把api的配置放到global中 然后在listview组件中获取然后使用
				type: "global/setListviewRowApiKey",
				payload: {
					value: obj,
					key: formDataKey
				}
			})
		}
		if (!isNull(apis) && !isNull(api_key) && !isNull(apis[api_key])) {//请求api 请求过来的数据 是否回写到data_store中
			// Modal.alert("api_key");
			dispatch({
				type: "form/query",
				payload: {
					apiInfo: apis[api_key],
					data: formData,
					callback: (result) => {
						if (result.error !== true) {
							let { data } = result;
							let { setFieldsValue, getFieldValue } = props;
							let { bundles } = back;
							let newObj = {};
							bundles && bundles.map(item => {
								let { name, field, value } = item;
								if (isNull(value)) {
									value = data[field]
								}
								newObj[name] = value;
							});
							for (let i in newObj) {
								getFieldValue(i);
								setFieldsValue({
									[i]: newObj[i]
								})
							}
						}
						else {
							console.log(result);
						}
					}
				}
			})
		}
		if (!isNull(datasets) && !isNull(dataset_key) && !isNull(datasets[dataset_key])) {//刷新dataset
			// Modal.alert("dataset_key");
			getDataSource({
				...props,
				dataset_key
			})
		}
	}
}
//处理 before
function handleBefore(props) {
	console.log("handleBefore");
	let { acfg: { before } } = props;
	if (isNull(before)) {
		console.log("before为空");
		handleDatasetKey(props)
	}
	else {
		let { confirm_title="提示",confirm, cancel_label = "取消", confirm_label = "确定" } = before;
		if (isNull(cancel_label) && isNull(confirm_label)) {//两个按钮都为空时,就显示确定按钮
			confirm_label = "确定"
		}
		console.log("before不为空", before, confirm);
		if (isNull(confirm)) {
			handleValidate(props)
		}
		else {
			confirm = calcField(confirm, props.formData);
			let btnArr = [];
			if (!isNull(cancel_label)) {
				btnArr.push(
					{
						text: cancel_label
					}
				)
			}
			if (!isNull(confirm_label)) {
				btnArr.push(
					{
						text: confirm_label,
						onPress: () => {
							handleValidate(props)
						}
					}
				)
			}
			Modal.alert(confirm_title, <div dangerouslySetInnerHTML={{ __html: confirm }}></div>, btnArr)
		}
	}
}
// 处理form 验证
function handleValidate(props) {
	let { acfg, validateFields } = props;
	let { isvalidate, isvalidate_msg } = acfg.before || {};
	if (isvalidate == 1) {
		console.log(validateFields)
		validateFields((err, value) => {
			if (!err) {
				handleDatasetKey(props);
			}
			else {
				if (isvalidate_msg) {
					MToast.fail(isvalidate_msg, 1.5, null, false)
				}
				console.log("验证未通过");
			}
		})
	}
	else {
		handleDatasetKey(props);
	}
}
//处理 api_key 和 dataset_key 只会执行一个 api_key优先级高
function handleDatasetKey(props) {
	let { acfg: { dataset_key, api_key, is_bluetooth_connect, bluetooth_connect_params = [] }, formData } = props;
	if (is_bluetooth_connect == 1) {
		if (browser.isInApp) {
			function bluetoothConnected() {
				// 连接成功
				handleAfter(props);
			}
			let newObj = {};
			bluetooth_connect_params.map(item => {
				let { name, field, value } = item;
				let key = field || name;
				if (isNull(value)) {
					value = formData[key]
				}
				if (!isNull(value)) {
					newObj[name] = value;
				}
			});
			console.log("is_bluetooth_connect", newObj);
			Func.registerHanderBridge("bluetoothConnected", bluetoothConnected)
			Func.callHander(bridge, "connectBluetooth", { ...newObj });
		}
		else {
			console.log("只能在APP中生效")
		}
		return;
	}
	let config;
	try {
		config = props.fd.config
	}
	catch (e) {
		config = props.config;
	}
	let { datasets, apis } = config || {};
	let goDataset = false;
	let goApi = false;
	if (!isNull(apis) && !isNull(api_key) && !isNull(apis[api_key])) {
		goApi = true;
	}
	else if (!isNull(datasets) && !isNull(dataset_key) && !isNull(datasets[dataset_key])) {
		goDataset = true;
	}
	if (goApi || goDataset) {
		if (goApi) {
			console.log("请求api", api_key)
			handleApiKeyQuery(props, apis[api_key])
		}
		else if (goDataset) {
			console.log("请求dataset", dataset_key)
			handleDatasetKeyQuery(props, datasets[dataset_key], dataset_key)
		}
	}
	else {
		console.log("是否提交")
		handelNeedSubmit(props);
	}
}
//处理 dataset_key
function handleDatasetKeyOld(props) {
	console.log("handleDatasetKey");
	let { acfg: { dataset_key } } = props;
	if (isNull(dataset_key)) {
		console.log("dataset_key为空");
		//如果dataset_key为空 去处理 need_submit
		handelNeedSubmit(props);
	}
	else {
		console.log("dataset_key不为空", dataset_key);
		let { fd: { config = {} } } = props;
		let { datasets } = config;
		let ds = datasets[dataset_key];
		if (isNull(ds)) {
			console.log("ds为空");
			// 找不到数据源时 去处理need_submit
			handelNeedSubmit(props);
		}
		else {
			console.log("ds不为空");
			// 数据源存在时 先执行数据源 如果数据源执行成功 就继续处理need_submit 执行失败 提示用户 不往下处理
			handleDatasetKeyQuery(props, ds, dataset_key)
		}
	}
}
// 处理need_submit
function handelNeedSubmit(props, result) {
	console.log("handelNeedSubmit", props);
	let { need_submit } = props.acfg;
	if (isNull(need_submit) || need_submit == 0) {
		handleAction(props, result)
	}
	else {
		console.log("需要提交", props);
		let { actions } = props.config || {};
		if (isNull(actions)) {
			console.log("没有配置提交所需要的actions");
		}
		else {
			//如果是提交的时候 需要进行的操作
			let { fd: { formData }, config: { data_store }, model = "form", dispatch } = props;
			let newFormData = handleDataType(data_store.fields, formData);
			dispatch({
				type: model + "/query",
				payload: {
					apiInfo: actions,
					isShowModal: true,
					isEditCreate: true,
					data: newFormData,
					callback: (result) => {
						console.log(result);
						if (result.error !== true) {
							let { formSuccessFunc } = props;
							handleAction(props, result);// 如果是提交的时候一般不应配置 after之后的操作
							formSuccessFunc && formSuccessFunc();// 提交成功之后 弹出窗，添加和修改弹窗内容不一样
						}
						else {
							// try{
							// MToast.fail(result.data.code,1,null,false)
							// }
							// catch(e){
							// }
						}
					}
				}
			})
		}
	}
}
//请求api 先判断是否需要扫码
function handleApiKeyQuery(props, api) {
	let { acfg, formData, dispatch, model = "form" } = props;
	let { is_scan } = acfg;
	function callbackQRCode(e) {
		console.log("apis", formData, props)
		if (!isNull(e)) {
			formData = {
				...formData,
				"_qr.value": e.qrcode
			}
		}
		dispatch({
			type: model + "/query",
			payload: {
				apiInfo: api,
				data: formData,
				callback: (result) => {
					if (result.error !== true) {
						handelNeedSubmit(props, result)
					}
					else {
						console.log(result);
					}
				}
			}
		})
	}
	if (is_scan == 1) {//如果是扫码 并且是在app中时才执行扫码
		if (browser.isInApp) {
			Func.callHander(bridge, "scanQRCode", {});
			Func.registerHanderBridge("callbackQRCode", callbackQRCode);
		}
	}
	else {
		callbackQRCode();
	}
}
//根据配置去请求数据 先判断是否需要扫码
function handleDatasetKeyQuery(props, ds, dataset_key) {
	let { acfg, formData, dispatch, model = "form" } = props;
	let { is_scan } = acfg;
	function callbackQRCode(e) {
		if (!isNull(e)) {
			formData = {
				...formData,
				"_qr.value": e.qrcode
			}
		}
		let { source_type } = ds;
		if (isNull(source_type)) {//如果source_type为空 就是请求api 否则就是请求数据源 根据id赋值赋值给数据源
			dispatch({
				type: model + "/query",
				payload: {
					apiInfo: ds.api,
					data: formData,
					callback: (result) => {
						if (result.error !== true) {
							handelNeedSubmit(props, result)
						}
						else {
							console.log(result);
						}
					}
				}
			})
		}
		else {
			if (source_type === "server") {
				getDataSource({
					...props,
					dataset_key,
					callback: (result) => {
						if (result.error !== true) {
							handelNeedSubmit(props, result)
						}
						else {
							console.log(result);
						}
					}
				})
			}
		}
	}
	if (is_scan == 1) {//如果是扫码 并且是在app中时才执行扫码
		if (browser.isInApp) {
			Func.callHander(bridge, "scanQRCode", {});
			Func.registerHanderBridge("callbackQRCode", callbackQRCode);
		}
	}
	else {
		callbackQRCode();
	}
}
//处理action
function handleAction(props, result) {
	let { acfg, formData, dispatch, location } = props;
	let { action_type, action = {}, after } = acfg;
	console.log("handleAction", "action_type=", action_type);
	//action_type 执行完dataset_key后执行 0无操作 1打开页面 2关闭 3重置
	//以下不回调：5打开系统浏览器 6打电话 7发短信 8打开通讯录(可指定联系人) 9打开系统相册
	if (isNull(action_type) || action_type == 0) {
		// return;
	}
	if (action_type == 1) {
		let { open_type = 1, params, title } = action;
		title = filterExp(title, formData);
		open_type = filterExp(open_type, formData);
		//open_type  1 新页面 2(使用H5的弹窗 不管是在H5中还是APP中) 3openWindow  4 在app中用native弹窗
		// app://
		if (open_type == 1 || open_type == 3) {
			console.log("open_type=1", params, props)
			let path = filterExp(params, formData);
			goToPage({
				dispatch, config: {
					url: path,
					state: {
						title
					},
					open_type
				}
			});
			setTimeout(() => {
				dispatch({
					type: "global/clearModal"
				})
			}, 300)
		}
		else if (open_type == 2) {
			let path = filterExp(params, formData);
			let pathname = path;
			let search;
			let pIndex = path.indexOf("?");
			if (pIndex != -1) {
				pathname = path.substring(0, pIndex);
				search = path.substring(pIndex)
			}
			search = encodeURI(search);
			let config = {
				pathname,
				search,
				_key: pathname + search
			};
			dispatch({
				type: "global/addModal",
				payload: {
					config
				}
			})
		}
		console.log(1)
	}
	else if (action_type == 2) {
		setTimeout(() => {
			let modalPath = JSON.parse(localStorage[MI_APP_CODE + "modalPath"]);
			if (!isNull(modalPath) && modalPath.length > 0) {
				let a = modalPath.filter(item => item._key === location._key);
				if (!isNull(a) && a.length > 0) {
					dispatch({
						type: "global/closeModal",
						payload: {
							_key: location._key
						}
					})
				}
				else {
					backToPrevious()
				}
			}
			else {
				backToPrevious()
			}
		}, 1000)
	}
	else if (action_type == 3) {
		let { resetFields, resetFunc } = props;
		resetFunc ? resetFunc() : resetFields();
	}
	else if (action_type == 4) {//调用扫码

	}
	handleAfter(props, result)
}
//处理after
function handleAfter(props, result = {}) {
	console.log("handleAfter");
	let { acfg, dispatch } = props;
	let { after } = acfg;
	if (isNull(after)) {
		return;
	}
	let { msg, callback } = after;
	if (!isNull(msg)) {
		MToast.info(msg, 1, null, false);
	}
	else {

	}
	if (isNull(callback)) {
		return
	}
	else {
		let { type, bundles } = callback;
		if (isNull(type) || type == 0) {
			return;
		}
		else if (type == 1) {//关闭页面，返回上一页
			if (!isNull(msg)) {
				setTimeout(() => {
					backToPrevious()
				}, 1000);
			}
			else {
				backToPrevious()
			}
		}
		else if (type == 2) {//往formData回写数据
			if (isNull(bundles) || bundles.length == 0) {
				return;
			}
			else {
				let { data = {} } = result;
				let { setFieldsValue, getFieldValue } = props;
				let newObj = {};
				bundles.map(item => {
					let { name, field, value } = item;
					if (isNull(value)) {
						value = data[field]
					}
					newObj[name] = value;
				});
				for (let i in newObj) {
					getFieldValue(i);
					setFieldsValue({
						[i]: newObj[i]
					})
				}
			}
		}
		else if (type == 3) {//打开新页面
			let { params } = callback;
			let { formData } = props;
			let path = filterExp(params, formData);
			setTimeout(() => {
				goToPage({
					dispatch, config: {
						url: path,
						open_type: 1
					}
				});
			}, 1000)
		}
		else if (type == 4) {//刷新当前页面
			if (!isNull(msg)) {
				setTimeout(() => {
					window.location.reload();
				}, 1000);
			}
			else {
				window.location.reload();
			}
		}
		else if (type == 5) {//刷新页面并打开新页面
			let { params } = callback;
			let { formData } = props;
			let path = filterExp(params, formData);

			setTimeout(() => {
				goToPage({
					dispatch, config: {
						url: path,
						open_type: 1
					}
				});
			}, 1000)
			setTimeout(() => {
				window.location.reload();
			}, 1100)
		}
		else if (type == 6) {//根据条件执行下一个next_event
			let { next_event } = callback;
			let { formData } = props;
			formData = {
				...formData,
				...result.data
			}
			next_event = calcField(next_event, formData);
			props = {
				...props,
				formData: formData
			}
			// console.log(props,next_event);
			MAction(props, next_event)//执行下一个event
		}
		else if (type == 7) {//刷新整个页面的数据源
			console.log("type7", props);
			let { formDataKey } = props;
			dispatch({
				type: "global/isChangeRefreshing",
				payload: {
					key: formDataKey
				}
			})
		}
	}
}
